<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

/**
 * 聊天主逻辑
 * 主要是处理 onMessage onClose
 */

use \GatewayWorker\Lib\Gateway;

class Events
{

    /**
     * 有消息时
     * @param int $client_id
     * @param mixed $message
     */
    public static function onMessage($client_id, $_msg)
    {
        // 客户端传递的是json数据
        $msg_data = json_decode($_msg);
        //调试时输出显示
        $msg_json_pre = json_encode($msg_data, 256 | 128);
        // debug
        echo "=============== onMessage =============== ";
        echo date('Y-m-d H:i:s') . " ===============>>\n";
        echo $msg_json_pre . "\n";
        echo "client   :{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} \n";
        echo "gateway  :{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']} \n";
        echo "client_id:{$client_id} \n";
        echo "session  :" . json_encode($_SESSION, 256 | 128) . "\n";

        // 客户端传递的是json数据
//        $message_data = json_decode($message, true);
        if (!$msg_data) {
            return;
        }

        // 根据类型执行不同的业务
        switch ($msg_data->type) {
            // 客户端回应服务端的心跳
            case 'pong':
                return;
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'login':
                // 判断是否有房间号
                if (!isset($msg_data->room_id)) {
                    $info = "room_id not set. client_ip:{$_SERVER['REMOTE_ADDR']}:" . $_msg;
                    throw new \Exception($info);
                }

                //把房间号昵称放到session中
                $room_id = $msg_data->room_id;
                $client_name = htmlspecialchars($msg_data->client_name);
                //$_SESSION['room_id'] = $room_id;
                //$_SESSION['client_name'] = $client_name;

                if (empty($room_id)) {
                    $_SESSION['room_id'] = $room_id;
                } else {
                    $_SESSION[$room_id] = $room_id;
                }
                if (empty($client_name)) {
                    $_SESSION['client_name'] = $client_name;
                } else {
                    $_SESSION[$client_name] = $client_name;
                }

                // 获取房间内所有用户列表 
                $clients_list = Gateway::getClientSessionsByGroup($room_id);
                //echo json_encode($clients_list, 256 | 128). "\n";
                foreach ($clients_list as $tmp_client_id => $item) {
                    $clients_list[$tmp_client_id] = $item['client_name'];
                }
                $clients_list[$client_id] = $client_name;

                // 转播给当前房间的所有客户端，xx进入聊天室 message {type:login, client_id:xx, name:xx} 
                $new_message = [
                    'type' => $msg_data->type,
                    'client_id' => $client_id,
                    'client_name' => htmlspecialchars($client_name),
                    'time' => date('Y-m-d H:i:s')
                ];
                Gateway::sendToGroup($room_id, json_encode($new_message, 256 | 128));
                Gateway::joinGroup($client_id, $room_id);

                // 给当前用户发送用户列表 
                $new_message['client_list'] = $clients_list;
                Gateway::sendToCurrentClient(json_encode($new_message));
                return;

            // 客户端发言 message: {type:say, to_client_id:xx, content:xx}
            case 'say':
                // 非法请求
                if (!isset($_SESSION['room_id'])) {
                    throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
                }
                $room_id = $_SESSION['room_id'];
                $client_name = $_SESSION['client_name'];

                // 私聊
                if ($msg_data->to_client_id != 'all') {
                    $new_message = [
                        'type' => 'say',
                        'from_client_id' => $client_id,
                        'from_client_name' => $client_name,
                        'to_client_id' => $msg_data->to_client_id,
                        'content' => "<b>对你说: </b>" . nl2br(htmlspecialchars($msg_data->content)),
                        'time' => date('Y-m-d H:i:s'),
                    ];
                    Gateway::sendToClient($msg_data->to_client_id, json_encode($new_message));
                    $new_message['content'] = "<b>你对" . htmlspecialchars($msg_data->to_client_name) . "说: </b>" . nl2br(htmlspecialchars($msg_data->content));
                    return Gateway::sendToCurrentClient(json_encode($new_message));
                }

                $new_message = [
                    'type' => 'say',
                    'from_client_id' => $client_id,
                    'from_client_name' => $client_name,
                    'to_client_id' => 'all',
                    'content' => nl2br(htmlspecialchars($msg_data->content)),
                    'time' => date('Y-m-d H:i:s'),
                ];
                return Gateway::sendToGroup($room_id, json_encode($new_message));
            //旧约企业下单
            case 'getBizOrder':
                //$room_id = $_SESSION['room_id'];
                $new_message = [
                    'type' => $msg_data->type,
                    'from_biz_id' => $msg_data->from_biz_id,
                    'to_user_id' => $msg_data->reclaim_id,
                    //'content' => $msg_data->content,
                    'time' => date('Y-m-d H:i:s'),
                ];
                //有接单的人员(回收班人员ID)
                if ($msg_data->reclaim_id) {
                    $new_message['content'] = '你有一个新的订单来了,赶快去接单!';
                    return Gateway::sendToGroup('jyhs_b', json_encode($new_message));
                } //无接单人员
                else {
                    $new_message['content'] = '有新的企业下单了,请马上为该订单指派人员!';
                    return Gateway::sendToGroup('jyhs_admin', json_encode($new_message));
                }
            //旧约企业下单(回收班通知)
            case 'getBizOrder_Notify':
                $new_message = [
                    'type' => $msg_data->type,
                    'to_biz_id' => $msg_data->to_biz_id,
                    //'content' => '你的订单已被接收!',
                    //'content' => $msg_data->content,
                    'time' => date('Y-m-d H:i:s'),
                ];
                if ($msg_data->to_reclaim_id) {
                    $c = new Common();
                    $res = $c->get_JYHSB_Orders(['Biz_ID' => $msg_data->to_biz_id,
                        'Reclaim_User_ID' => $msg_data->to_reclaim_id,
                        'Order_Status' => 0]);
                    if (!$res) {
                        return 0;
                    }
                    $new_message['content'] = '你有一个新的订单来了,赶快去接单!';
                    $new_message['to_user_id'] = $msg_data->to_reclaim_id;
                    Gateway::sendToGroup('jyhs_b', json_encode($new_message));
                }
                $new_message['content'] = '你的订单已被接收!';
                return Gateway::sendToGroup('jyhs_user', json_encode($new_message));
            //旧约用户下单
            case 'getUserOrder':
                //$room_id = $_SESSION['room_id'];
                $new_message = [
                    'type' => $msg_data->type,
                    'from_user_id' => $msg_data->from_user_id,
                    'to_user_id' => $msg_data->reclaim_id,
                    'time' => date('Y-m-d H:i:s'),
                ];
                //有接单的人员(回收班人员ID)
                if ($msg_data->reclaim_id) {
                    $new_message['content'] = '你有一个新的订单来了,赶快去接单!';
                    return Gateway::sendToGroup('jyhs_b', json_encode($new_message));
                } //无接单人员
                else {
                    $new_message['content'] = '有新的企业下单了,请马上为该订单指派人员!';
                    return Gateway::sendToGroup('jyhs_admin', json_encode($new_message));
                }
            //旧约用户下单(回收班通知)
            case 'getUserOrder_Notify':
                $new_message = [
                    'type' => $msg_data->type,
                    'to_user_id' => $msg_data->to_user_id,
                    //'content' => '你的订单已被接收!',
                    //'content' => $msg_data->content,
                    'time' => date('Y-m-d H:i:s'),
                ];
                $new_message['content'] = '你的订单已被接收!';
                return Gateway::sendToGroup('jyhs_user', json_encode($new_message));
            //旧约订单完成
            case 'finishOrder':
            //旧约订单取消
            case 'cancelOrder':
                $new_message = [
                    'type' => $msg_data->type,
                    'to_user_id' => $msg_data->reclaim_id,
                    'content' => $msg_data->type == 'cancelOrder' ? '你的订单已被取消' : '你的订单已完成',
                    'time' => date('Y-m-d H:i:s'),
                ];
                return Gateway::sendToGroup('jyhs_b', json_encode($new_message));
            //旧约回收人员支付
            case 'payOrder':
                $new_message = [
                    'type' => $msg_data->type,
                    'content' => '你的订单' . $msg_data->money . '元已支付!',
                    'time' => date('Y-m-d H:i:s'),
                ];
                //用户下的单
                if (isset($msg_data->to_user_id)) {
                    $new_message['to_user_id'] = $msg_data->to_user_id;
                }
                //企业下的单
                else {
                    $new_message['to_biz_id'] = $msg_data->to_biz_id;
                }
                return Gateway::sendToGroup('jyhs_user', json_encode($new_message));
        }
    }

    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        // debug
        echo "--------------- onClose --------------- ";
        echo date('Y-m-d H:i:s') . " ---------------\n";
        echo "client   :{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} \n";
        echo "gateway  :{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']} \n";
        echo "client_id:{$client_id} \n";
        echo "onClose  :''\n";
        echo "session  :" . json_encode($_SESSION, 256 | 128) . " \n";

        // 从房间的客户端列表中删除
        if (isset($_SESSION['room_id'])) {
            $room_id = $_SESSION['room_id'];
            $new_message = [
                'type' => 'logout',
                'from_client_id' => $client_id,
                'from_client_name' => $_SESSION['client_name'],
                'time' => date('Y-m-d H:i:s')
            ];
            Gateway::sendToGroup($room_id, json_encode($new_message));
        }
    }

}
